//
//  CHUploadDetailController.m
//  CarFile
//
//  Created by 陈浩 on 2017/7/11.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHUploadDetailController.h"
#import "CHRepairDetailController.h"
#import "CHDemoViewController.h"
#import "CHNouploadCell.h"
#import "CHNouploadModel.h"
#import "CHUploadCell.h"
@interface CHUploadDetailController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic ,strong) UIScrollView *mainScrollView;
@property (nonatomic ,strong) UITableView *nouploadTableView;
@property (nonatomic ,strong) UITableView *uploadTableView;
@property (nonatomic ,strong) UISegmentedControl *segmentedControl;
@property (nonatomic ,assign) int page;
@property (nonatomic ,assign) int index;
@property (nonatomic ,strong) NSMutableArray *nouploadDatas;
@property (nonatomic ,strong) NSMutableArray *uploadDatas;
@end

@implementation CHUploadDetailController
-(NSMutableArray *)uploadDatas{
    if (!_uploadDatas) {
        _uploadDatas = [NSMutableArray array];
    }
    return _uploadDatas;
    
}
-(NSMutableArray *)nouploadDatas{
    if (!_nouploadDatas) {
        _nouploadDatas = [NSMutableArray array];
    }
    return _nouploadDatas;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = KRGB(231, 231, 249);
    
    [self setTitleLabel];

    [self setSegmentedControl];
   
    [self getUploadData];
    
    [self setupMainScrollView];

}

-(void)setTitleLabel{
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenW - 30, 44)];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.numberOfLines = 0;
    titleLabel.text = [NSString stringWithFormat:@"%@有企业%@家，截止到目前，有%@家企业完成数据上传，上传率%@。",self.model.areacn,self.model.comnum,self.model.uploadnum,self.model.uploadrate];
    
    titleLabel.textColor = [UIColor colorWithHexString:@"999999" alpha:1.0f];
    [self.view addSubview:titleLabel];

    
}

-(void)setSegmentedControl{
    
    NSArray *segmentedArray = [NSArray arrayWithObjects:@"未上传",@"已上传", nil];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedArray];
    segmentedControl.frame = CGRectMake(0, 0, 100, 30);
    segmentedControl.selectedSegmentIndex = 0;
    
    [segmentedControl addTarget:self  action:@selector(didClicksegmentedControlAction:)
     
               forControlEvents:UIControlEventValueChanged];
    self.segmentedControl = segmentedControl;
    [self.navigationItem setTitleView:self.segmentedControl];
    
}



-(void)didClicksegmentedControlAction:(UISegmentedControl *)seg{
    
    
    [self.mainScrollView setContentOffset:CGPointMake(seg.selectedSegmentIndex *UIScreenW, 0) animated:YES];

    
}


#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
  
    int tag = (int)scrollView.contentOffset.x/self.view.size.width +100 ;

    self.segmentedControl.selectedSegmentIndex = tag - 100;

    
}


-(void)getNouploadData{
    _page = 1;
   
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    params[@"levels"] = self.levels;
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnouploadlistbycompany" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"%@",result);
       [self.nouploadDatas removeAllObjects];
        [self.nouploadTableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNouploadModel *model = [CHNouploadModel objectWithKeyValues:dict];
                [self.nouploadDatas addObject:model];
            }
            
            self.nouploadTableView.placeholderImage = @"data_null";
            self.nouploadTableView.placeholder = @"暂时没有数据哦~";
            [self.nouploadTableView reloadData];
        }
    }];
}




-(void)getUploadData{
    _index = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"levels"] = self.levels;
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovuploadlistbycompany" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
    
        [self.uploadDatas removeAllObjects];
        [self.uploadTableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNouploadModel *model = [CHNouploadModel objectWithKeyValues:dict];
                [self.uploadDatas addObject:model];
            }
            self.uploadTableView.placeholderImage = @"data_null";
            self.uploadTableView.placeholder = @"暂时没有数据哦~";
            [self.uploadTableView reloadData];
        }
    }];
}

-(void)loadMoreUploadData{
    _index++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"levels"] = self.levels;
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovuploadlistbycompany" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
  ;
        [self.uploadTableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNouploadModel *model = [CHNouploadModel objectWithKeyValues:dict];
                [self.uploadDatas addObject:model];
            }
            [self.uploadTableView reloadData];
        }
    }];
    
}

-(void)loadMoreNouploadData{
    _page++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"levels"] = self.levels;
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnouploadlistbycompany" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        

        [self.nouploadTableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNouploadModel *model = [CHNouploadModel objectWithKeyValues:dict];
                [self.nouploadDatas addObject:model];
            }
            [self.nouploadTableView reloadData];
        }
    }];
    
}

-(void)setupMainScrollView{
    
    
    UIScrollView *mainScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0,  44, UIScreenW, UIScreenH  -64 -44)];
    mainScrollview.delegate = self;
    mainScrollview.pagingEnabled = YES;
    mainScrollview.scrollEnabled = YES;
    mainScrollview.bounces = NO;
    mainScrollview.showsHorizontalScrollIndicator = NO;
    mainScrollview.showsVerticalScrollIndicator = NO;
//    //    mainScrollview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:mainScrollview];
    self.nouploadTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, mainScrollview.h)];
    self.nouploadTableView.backgroundColor = KRGB(239, 239, 249);
    self.nouploadTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.nouploadTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.nouploadTableView.delegate = self;
    self.nouploadTableView.dataSource = self;

    // 下拉刷新
    self.nouploadTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        [self getNouploadData];
        
    }];

    self.nouploadTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreNouploadData];
       
    }];
    self.nouploadTableView.mj_footer.automaticallyHidden = self.nouploadDatas.count > 0 ? NO : YES;
    [self.nouploadTableView.mj_header beginRefreshing];
    
    [mainScrollview addSubview:self.nouploadTableView];
    
   
    
    self.uploadTableView = [[UITableView alloc] initWithFrame:CGRectMake(UIScreenW, 0, UIScreenW, mainScrollview.h)];
    self.uploadTableView.backgroundColor = KRGB(239, 239, 249);
    self.uploadTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 下拉刷新
    self.uploadTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.uploadTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        [self getUploadData];

    }];
    self.uploadTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreUploadData];
    }];
    self.uploadTableView.delegate = self;
    self.uploadTableView.dataSource = self;
    [mainScrollview addSubview:self.uploadTableView];
    
    mainScrollview.contentSize = CGSizeMake(UIScreenW *2, 0);
    self.mainScrollView = mainScrollview;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.nouploadTableView) {
        return self.nouploadDatas.count;
    }
    return self.uploadDatas.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.nouploadTableView) {
        CHNouploadCell *cell = [CHNouploadCell cellForTableView:tableView];
        __weak typeof(self) weakSelf = self;
        cell.block = ^{

            
            CHDemoViewController *vc = [[CHDemoViewController alloc] init];
            CHExceptionlistInfoModel *model = weakSelf.nouploadDatas[indexPath.row];
            
            vc.datas = model.nouploaddata[@"time"];
            [weakSelf.navigationController pushViewController:vc animated:YES];
         
        };
        cell.model = self.nouploadDatas[indexPath.row];
        return cell;
    }else{
        
        CHUploadCell *cell = [CHUploadCell cellForTableView:tableView];
      
        cell.model = self.uploadDatas[indexPath.row];
        return cell;
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.nouploadTableView) {
        return 150;
    }
    return 110;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id obj = [LongriseRouter openURL:@"CHRepairDetailController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    //判断该类是否可以传参数
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            CHNouploadModel *model = [[CHNouploadModel alloc] init];
                if (tableView == self.nouploadTableView) {
                    model =  self.nouploadDatas[indexPath.row];
                }else{
                    model = self.uploadDatas[indexPath.row];
                }
                params[@"companyid"] = model.companyid;
               params[@"areaid"] = model.areaid;
            
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:params block:^(id obj) {
                
                
            }];
        }
    }
    
    
}


#pragma mark LongriseRouterDelegater代理回调方法
-(void)setParams:(id)obj block:(LongriseRouterBlock)block
{
  
    if (obj && [obj isKindOfClass:[NSMutableDictionary class]]) {
        
        NSMutableDictionary *dict = obj;
        self.startTime = dict[@"starttime"];
        self.endTime = dict[@"endtime"];
        self.model = dict[@"model"];
        self.levels = dict[@"levels"];

    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
